package com.atguigu.day04;

import com.atguigu.bean.Event;
import com.mysql.jdbc.Driver;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Flink04_Sink_Mysql_Custom {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.获取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        SingleOutputStreamOperator<Event> map = streamSource.map(new MapFunction<String, Event>() {
            @Override
            public Event map(String value) throws Exception {
                String[] split = value.split(",");
                return new Event(split[0], split[1], Long.parseLong(split[2]));
            }
        });

        //TODO 3.将数据写入Mysql
        map.addSink(new MySink());
        env.execute();
    }
//    public static class MySink implements SinkFunction<Event>{
    public static class MySink extends RichSinkFunction<Event> {

    private Connection connection;
    private PreparedStatement pstm;

    @Override
    public void open(Configuration parameters) throws Exception {
        System.out.println("创建链接");
        //1.创建链接
        connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/test", "root", "123456");
        //2.创建语句执行者
        pstm = connection.prepareStatement("insert into clicks values(?,?)");

    }


    @Override
        public void invoke(Event value, Context context) throws Exception {

            pstm.setString(1,value.user);
            pstm.setString(2, value.url);
            pstm.execute();
        }

    @Override
    public void close() throws Exception {
        System.out.println("关闭链接");
        pstm.close();
        connection.close();
    }

}
}
